package com.leo.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @ClassName: FileHandlerController
 * @Description: 处理文件的上传下载
 * @Author: leo825
 * @Date: 2020-02-02 22:27
 * @Version: 1.0
 */
@Controller
public class FileHandlerController {

    /**
     * 文件上传
     *
     * @param multipartFil
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@RequestParam(value = "file") MultipartFile multipartFil, HttpServletRequest request) throws IOException {
        if (!multipartFil.isEmpty()) {
            //文件标签名
            System.out.println(multipartFil.getName());
            //上传文件名称
            System.out.println(multipartFil.getOriginalFilename());
            //文件大小
            System.out.println(multipartFil.getSize());
            //上传文件的类型
            System.out.println(multipartFil.getContentType());

            String fileDirStr = request.getServletContext().getRealPath("/uploadFile");
            String filename = multipartFil.getOriginalFilename();
            System.out.println(fileDirStr);
            File fileDir = new File(fileDirStr);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            File file1 = new File(fileDir, filename);
            multipartFil.transferTo(file1);
        }
        return "success";
    }

    /**
     * 下载文件：
     * 通过Spring提供的这种对象，这种下载具有局限性，文件太大会导致内存溢出异常
     *
     * @param request
     * @param filename
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam String filename) throws IOException {
        String fileDirStr = request.getServletContext().getRealPath("/uploadFile");
        File file = new File(fileDirStr, filename);
        byte[] body = FileUtils.readFileToByteArray(file);
        //设置下载名称，否则乱码
        String downloadFilename = new String(file.getName().getBytes("utf-8"), "iso-8859-1");
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置文件类型
        httpHeaders.add("Content-Disposition", "attchement;filename=" + downloadFilename);

        ResponseEntity responseEntity = new ResponseEntity(body, httpHeaders, HttpStatus.OK);
        return responseEntity;
    }

    /**
     * 使用字节流直接输出，实现类似上面
     *
     * @param request
     * @param response
     * @param filename
     */
    @RequestMapping(value = "/download2", method = RequestMethod.GET)
    public void download2(HttpServletRequest request, HttpServletResponse response, @RequestParam String filename) throws IOException {
        //获取主机文件
        String fileDirStr = request.getServletContext().getRealPath("/uploadFile");
        File file = new File(fileDirStr, filename);
        byte[] outByte = FileUtils.readFileToByteArray(file);
        //设置下载名称，否则乱码
        String downloadFilename = new String(file.getName().getBytes("utf-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attchement;filename=" + downloadFilename);
        response.getOutputStream().write(outByte);
        response.getOutputStream().close();
    }

    /**
     * 普通的输出输出流下载
     *
     * @param request
     * @param response
     * @param filename
     * @throws IOException
     */
    @RequestMapping(value = "/download3", method = RequestMethod.GET)
    public void download3(HttpServletRequest request, HttpServletResponse response, @RequestParam String filename) throws IOException {
        //获取主机文件
        String fileDirStr = request.getServletContext().getRealPath("/uploadFile");
        File file = new File(fileDirStr, filename);
        InputStream inputStream = new FileInputStream(file);

        //设置下载名称，否则乱码
        String downloadFilename = new String(file.getName().getBytes("utf-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attchement;filename=" + downloadFilename);
        OutputStream os = response.getOutputStream();
        byte[] bf = new byte[2048];
        int len;
        while ((len = inputStream.read(bf)) > 0) {
            os.write(bf, 0, len);
        }
        os.close();
        inputStream.close();
    }
}
